import { useEffect, useState } from "react";
import { Edit2, Plus, Trash2 } from "lucide-react";
import { useSnapshot } from "valtio";
import { coreState } from "@/store/core";
import type { NavLinkItem } from "@/types";
import { Alert, AlertDescription } from "./ui/alert";
import { Button } from "./ui/button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "./ui/dialog";
import { Input } from "./ui/input";

interface BookmarkDialogProps {
  open: boolean;
  onClose: () => void;
  onSave: (bookmark: Omit<NavLinkItem, "id">) => void;
  initialData?: NavLinkItem;
  title: string;
}

function NavLinkDialog({ open, onClose, onSave, initialData, title }: BookmarkDialogProps) {
  const [name, setName] = useState(initialData?.name || "");
  const [url, setUrl] = useState(initialData?.url || "");
  const [background, setBackground] = useState(initialData?.background || "");
  const [icon, setIcon] = useState(initialData?.icon || "");
  const [error, setError] = useState<string | null>(null);

  // 当 initialData 变化时更新表单字段
  useEffect(() => {
    if (initialData) {
      setName(initialData.name);
      setUrl(initialData.url);
      setBackground(initialData.background || "");
      setIcon(initialData.icon || "");
    } else {
      // 如果是添加新书签，重置表单
      setName("");
      setUrl("");
      setBackground("");
      setIcon("");
    }
    // 清除任何错误消息
    setError(null);
  }, [initialData, open]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    try {
      new URL(url); // 验证URL
      onSave({ name, url, icon, background });
      onClose();
    } catch (err) {
      const error = err as Error;
      console.error("验证失败的具体原因:", error.message);
      setError("Please enter a valid URL (including http:// or https://)");
    }
  };

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
          <DialogDescription>Enter the bookmark details below</DialogDescription>
        </DialogHeader>

        {error && (
          <Alert variant="destructive">
            <AlertDescription>{error}</AlertDescription>
          </Alert>
        )}

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="text-sm font-medium mb-1 block">Name</label>
            <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Enter bookmark name" required />
          </div>
          <div>
            <label className="text-sm font-medium mb-1 block">URL</label>
            <Input value={url} onChange={(e) => setUrl(e.target.value)} placeholder="https://example.com" required />
          </div>
          <div>
            <label className="text-sm font-medium mb-1 block">背景色</label>
            <Input value={background} onChange={(e) => setBackground(e.target.value)} type="color" required />
          </div>
          <div>
            <label className="text-sm font-medium mb-1 block">Icon URL (optional)</label>
            <Input
              value={icon}
              onChange={(e) => setIcon(e.target.value)}
              placeholder="https://example.com/favicon.ico"
            />
          </div>
          <div className="flex justify-end gap-2">
            <Button type="button" variant="outline" onClick={onClose}>
              Cancel
            </Button>
            <Button type="submit">Save</Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
}

export default function NavLink() {
  const snapCore = useSnapshot(coreState);

  const [editBookmark, setEditBookmark] = useState<NavLinkItem | null>(null);
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState<string | null>(null);
  const [editMode, setEditMode] = useState(false);

  const handleBookmarkClick = (url: string, e: React.MouseEvent) => {
    // 如果在编辑模式下或点击的是操作按钮，不要打开链接
    if (editMode || (e.target as HTMLElement).closest("button")) {
      return;
    }

    try {
      new URL(url);
      window.open(url, "_self");
    } catch {
      alert(`Invalid URL: ${url}`);
    }
  };

  const handleSaveNavLink = (bookmarkData: Omit<NavLinkItem, "id">) => {
    if (editBookmark) {
      // 编辑现有书签
      coreState.setNavLinks(
        coreState.settings.navLinks.map((b) =>
          b.id === editBookmark.id ? { ...bookmarkData, id: editBookmark.id } : b,
        ),
      );
    } else {
      // 添加新书签
      const newBookmark = {
        ...bookmarkData,
        id: Math.random().toString(36).substr(2, 9),
      };

      coreState.setNavLinks([...coreState.settings.navLinks, newBookmark]);
    }
  };

  const handleDeleteNavLink = async (id: string) => {
    coreState.setNavLinks(coreState.settings.navLinks.filter((b) => b.id !== id));
  };

  const itemCls =
    " w-28 h-28 p-4 flex flex-col items-center rounded-xl border bg-card/90 backdrop-blur-sm hover:bg-card/80 hover:shadow-lg transition-all duration-300 cursor-pointer transform hover:-translate-y-1 ";

  return (
    <>
      <div className="flex justify-end items-center mb-4">
        <Button
          variant={editMode ? "default" : "outline"}
          size="sm"
          onClick={() => setEditMode(!editMode)}
          className={
            editMode
              ? "bg-white text-black hover:bg-white/90 transition-all duration-300"
              : "bg-black/40 text-white border-white/30 hover:bg-black/60 transition-all duration-300"
          }
        >
          <Edit2 className="h-4 w-4 mr-2" />
          {editMode ? "Exit Edit Mode" : "Edit Links"}
        </Button>
      </div>

      <div className="flex flex-wrap gap-4">
        {snapCore.settings &&
          snapCore.settings.navLinks &&
          snapCore.settings.navLinks.map((item) => (
            <div
              key={item.id}
              className={`${itemCls} relative border-border/50 bg-[var(--muted)] ${editMode ? "ring-2 ring-primary/20" : ""}`}
              onClick={(e) => handleBookmarkClick(item.url, e)}
            >
              <div className="relative border-1 rounded-lg mb-3 bg-[var(--sidebar)]">
                <img
                  src={item.icon || `https://www.google.com/s2/favicons?domain=${item.url}&sz=128`}
                  className="w-12 h-12 rounded-lg object-cover border border-white/10"
                  style={{ backgroundColor: item.background }}
                  alt={item.name}
                />
                {editMode && (
                  <div
                    className={`absolute inset-0 bg-black/20 rounded-lg flex items-center justify-center backdrop-blur-sm group-hover:opacity-100 transition-all duration-300`}
                  >
                    <div className="flex gap-3">
                      <Button
                        size="icon"
                        variant="secondary"
                        className="h-9 w-9 bg-blue-500 hover:bg-primary/10 hover:text-primary"
                        onClick={() => setEditBookmark(item)}
                      >
                        <Edit2 className="h-4 w-4" />
                      </Button>
                      <Button
                        size="icon"
                        variant="destructive"
                        className="h-9 w-9 hover:bg-destructive/90"
                        onClick={() => setShowDeleteDialog(item.id)}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                )}
              </div>
              <div className="text-center w-full">
                <h3 className="text-sm font-medium truncate">{item.name}</h3>
              </div>
            </div>
          ))}

        {/* 添加按钮 */}
        <div
          className={`${itemCls} justify-center border-dashed border-primary/30 hover:border-primary/50`}
          onClick={() => setShowAddDialog(true)}
        >
          <div className="w-12 h-12 rounded-lg mb-3 flex items-center justify-center bg-primary/10 text-primary">
            <Plus className="w-6 h-6" />
          </div>
          <span className="text-sm font-medium text-primary">Add</span>
        </div>
      </div>

      {/* 编辑书签对话框 */}
      <NavLinkDialog
        open={!!editBookmark}
        onClose={() => setEditBookmark(null)}
        onSave={handleSaveNavLink}
        initialData={editBookmark || undefined}
        title="Edit Bookmark"
      />

      {/* 添加书签对话框 */}
      <NavLinkDialog
        open={showAddDialog}
        onClose={() => setShowAddDialog(false)}
        onSave={handleSaveNavLink}
        title="Add Bookmark"
      />

      {/* 删除确认对话框 */}
      <Dialog open={!!showDeleteDialog} onOpenChange={() => setShowDeleteDialog(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Delete Bookmark</DialogTitle>
            <DialogDescription>
              Are you sure you want to delete this bookmark? This action cannot be undone.
            </DialogDescription>
          </DialogHeader>
          <div className="flex justify-end gap-2">
            <Button variant="outline" onClick={() => setShowDeleteDialog(null)}>
              Cancel
            </Button>
            <Button
              variant="destructive"
              onClick={() => {
                if (showDeleteDialog) {
                  handleDeleteNavLink(showDeleteDialog);
                  setShowDeleteDialog(null);
                }
              }}
            >
              Delete
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
}
